package com.lkd.handler;

import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-07-22 9:25
 */
@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
@Slf4j
public class CloseOrderHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;


    @Override
    public void process(String jsonMsg) throws IOException {
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);

        //判断当前订单是否未支付，如果未支付关闭订单
        OrderEntity order = orderService.getByOrderNo(orderCheck.getOrderNo());
        if(order == null){
            log.error("订单已经被删除，订单编号是:" + orderCheck.getOrderNo());
            return;
        }

        if(VMSystem.PAY_STATUS_NOPAY.equals(order.getPayStatus())){
            //未支付，关闭订单
            order.setStatus(VMSystem.ORDER_STATUS_INVALID);
            order.setCancelDesc("未支付自动超时取消");
            orderService.updateById(order);
        }

        //微信支付交易关闭
        WxPayParam wxPayParam = new WxPayParam();
        wxPayParam.setOutTradeNo(orderCheck.getOrderNo());
        try {
            wxPayTemplate.closeOrder(wxPayParam);
        } catch (Exception e) {
            log.error("微信关闭支付单失败",e);
        }
    }
}
